<template>
  <div class="my-image">
    <!-- 图片按钮 -->
    <div class="btn-img" @click="openDialog()">
      <!-- <img :src="previewImg" alt /> -->
      <img :src="value || previewImg" alt />
    </div>
    <!-- 对话框 -->
    <el-dialog :visible.sync="dialogVisible" width="720px">
      <!-- tabs组件 v-model="activeName" 激活的选项卡的name属性值-->
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="素材库" name="images">
          <!-- 按钮 -->
          <el-radio-group @change="toggleList()" v-model="reqParams.collect" size="small">
            <el-radio-button :label="false">全部</el-radio-button>
            <el-radio-button :label="true">收藏</el-radio-button>
          </el-radio-group>
          <!-- 列表 -->
          <div class="img-list">
            <div :class="{selected:selectedImgUrl===item.url}" @click="selectedImg(item.url)"
             class="img-item" v-for="item in images" :key="item.id">
              <img :src="item.url" alt />
            </div>
          </div>
          <!-- 分页 -->
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="reqParams.per_page"
            :current-page="reqParams.page"
            @current-change="changePager"
          ></el-pagination>
        </el-tab-pane>
             <el-tab-pane label="上传图片" name="upload">
                <el-upload
                    class="avatar-uploader"
                    action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
                    name="image"
                    :headers="headers"
                    :show-file-list="false"
                    :on-success="uploadSuccess">
                    <img v-if="uploadImgUrl" :src="uploadImgUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmImg()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import auth from '@/utils/auth'
// 打包因动态绑定无法打包的图片资源 （导致服务器无法解析）
import img from '../assets/default.png'
export default {

  name: 'my-image',
//   接收父组件数据
  props: ['value'],
  data () {
    return {
          // 当前上传的图片地址
      uploadImgUrl: null,
      // 请求头数据
      headers: { Authorization: `Bearer ${auth.getUser().token}` },
    // 当前选中的图片地址
      selectedImgUrl: null,
      // 控制对话框显示隐藏
      dialogVisible: false,
      // 当激活选项卡的name
      activeName: 'images',
       // 查询素材参数对象
      reqParams: {
        collect: false,
        page: 1,
        per_page: 8
      },
       // 素材列表
      images: [],
      // 总条数
      total: 0,
      previewImg:img
    }
  },
  methods: {
    // 上传图片成功
    uploadSuccess (response) {
      // 预览
      this.uploadImgUrl = response.data.url
    },
    // 记录点击的图片
    selectedImg (url) {
      this.selectedImgUrl = url
    },
    // 切换列表
    toggleList () {
      this.reqParams.page = 1
      this.getImages()
    },
    // 进行分页
    changePager (np) {
      this.reqParams.page = np
      this.getImages()
    },
    openDialog () {
      this.dialogVisible = true
       // 获取素材列表数据
       this.getImages()
        this.activeName = 'images'
      this.selectedImgUrl = null
      this.uploadImgUrl = null
    },
    // 获取图片素材
    async getImages () {
      const res = await this.$http.get('user/images', {
        params: this.reqParams
      })
      this.images = res.data.data.results
      this.total = res.data.data.total_count
    },
     // 确认图片
    confirmImg () {
      if (this.activeName === 'images') {
        // 激活 素材库
        if (!this.selectedImgUrl) return this.$message.warning('请选择一张图片')
        // this.previewImg = this.selectedImgUrl
        this.$emit('input', this.selectedImgUrl)
      } else {
        // 激活 上传图片
        if (!this.uploadImgUrl) return this.$message.warning('请上传一张图片')
        // this.previewImg = this.uploadImgUrl
         this.$emit('input', this.uploadImgUrl)
      }
      // 关闭对话框
      this.dialogVisible = false
        //   去做其他组件的业务 触发自定义·事件confirm
        this.$emit('confirm')
    },
  }
}
</script>

<style scoped lang='less'>
.my-image {
  display: inline-block;
  margin-right: 20px;
  .btn-img {
    width: 150px;
    height: 150px;
    border: 1px dashed #ddd;
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
  .img-list{
      .img-item{
          width: 150px;
          height: 120px;
          border:1px dashed #ddd;
          display: inline-block;
          margin-left: 15px;
          position: relative;
          img{
              width: 100%;
              height: 100%;
              display: block;
          }
        &.selected::after {
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,.3) url(../assets/selected.png) no-repeat center / 50px auto;
        }
      }
  }
}
</style>